<?php

namespace Wonfu\Core\Database;

use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class CakeQueryWrapper extends \Cake\ORM\Query
{
    private $mapper;


    /**
     * @param mixed $mapper
     */
    public function setMapper($mapper): void
    {
        $this->mapper = $mapper;
    }



    /**
     * @param mixed $data
     * @param string $mapper
     * @return mixed
     */
    public static function ObjectMapper($data, $mapper)
    {
        if(is_null($data)){
            return null;
        }
        $encoders = [new XmlEncoder(), new JsonEncoder()];
        $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
        $normalizers = [new ObjectNormalizer(null, null, null, $extractor),
            new ArrayDenormalizer(), new JsonSerializableNormalizer()];
        $serializer = new Serializer($normalizers, $encoders);
        return $serializer->deserialize($data, $mapper, 'json', [
            ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]);
    }

    public function firstPoPoObject(){
        $result = $this->first();
        return self::ObjectMapper($result,$this->mapper);
    }

    public function fetchPoPoObject(){
        $result = json_encode($this->all()->toArray());
        return self::ObjectMapper($result,$this->mapper.'[]');
    }

}